import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPCopyFileServer {
    public static void main(String[] args) {
        try {
            // 设置服务器使用的端口号
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("文件传输服务器已启动，等待客户端连接");
            // 等待客户端连接
            Socket server = serverSocket.accept();
            System.out.println("客户端与服务器已经连接成功");

            InputStream inputStream = server.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line = null;

            line = bufferedReader.readLine();
            System.out.println("文件名：" + line);
            line = bufferedReader.readLine();

            long size = Long.parseLong(line);
            System.out.println("大小：" + line);

            long temp = 0;
            FileOutputStream fileOutputStream = new FileOutputStream("copy " + line);
            while ((line = bufferedReader.readLine())!= null){
                fileOutputStream.write(line.getBytes());
                temp += line.getBytes().length;
                System.out.println(temp);

            }

            String info = "发送成功";
            OutputStream outputStream = server.getOutputStream();
            outputStream.write(info.getBytes());
            outputStream.close();

            inputStream.close();
            server.close();
            serverSocket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
